console.time("time");
function getText(title) {
  // 缓存DOM查询结果
  const elements = document.querySelectorAll(".api-title");
  const apiTitleRows = [];
  elements.forEach((item) => {
    if (item.innerText === title) {
      apiTitleRows.push(...item.nextSibling.querySelectorAll(".ant-table-row"));
    }
  });
  let minLevel = 100,
    maxLevel = 0,
    objectArray = [],
    load = { datas: [] },
    textLoad = "";
  // 简化objectArray的初始化
  elements.forEach((item) => {
    let minLevel = 100,
      maxLevel = 0,
      level;
    if (item.className.split("").at(-1) > maxLevel)
      maxLevel = item.className.split("").at(-1);
    if (item.className.split("").at(-1) < minLevel)
      minLevel = item.className.split("").at(-1);
    objectArray.push({
      class: level,
      key: item.children[0].innerText,
      title: item.children[1].innerText,
      type: item.children[title === "请求参数" ? 4 : 2].innerText,
      require: title === "请求参数" ? item.children[3].innerText : "",
    });
  });
  // 优化循环逻辑
  for (let level = maxLevel; level >= minLevel; level--) {
    let startIndex = objectArray.findIndex((item) => item.class === level);
    let endIndex = startIndex;
    while (
      endIndex < objectArray.length &&
      objectArray[endIndex].class === level
    ) {
      endIndex++;
    }
    if (startIndex !== -1) {
      if (load.datas.length === 0) load.start = startIndex;
      load.datas.push(...objectArray.slice(startIndex, endIndex));
      if (load.datas.length > 0) {
        load.end = endIndex;
        generate(
          {
            class: level,
            key: title === "请求参数" ? "request" : "response",
            title: title === "请求参数" ? "request" : "response",
            type: "interface",
          },
          load
        );
        objectArray.splice(startIndex, endIndex - startIndex);
        load = { datas: [] };
      }
    }
  }
  return textLoad;
}
function generate(item, load) {
  const properties = load.datas.map((value) => {
    const type = getType(value.type);
    return `\t${value.key}${
      value.require === "false" ? "?" : ""
    }: ${type}; // ${value.title}\n`;
  });

  let temp = `export interface ${format(item.key)} {\n${properties.join(
    ""
  )}\n}`;
  textLoad += temp;
}
function getType(type) {
  const typeMap = {
    integer: "number",
    number: "number",
    string: "string",
    boolean: "boolean",
    分页返回: (value) => `${format(value.key)}`,
    array: (value) => `${format(value.key)}[]`,
  };
  return typeMap[type.toLowerCase()] || "any";
}

function format(string) {
  return string.charAt(0).toUpperCase() + string.slice(1);
}
// 使用Promise.all来并行执行两个getText调用
Promise.all([getText("请求参数"), getText("响应参数")]).then((results) => {
  console.log(results[0] + "\n" + results[1]);
  console.timeEnd("time");
});
